<?php
/*****************
*作者：jeff.liu
*联系方式：13810908686
*电子邮件：ljf1279@yeah.net
******************/
class Object
{
	function __construct($arr = NULL)
	{
		if(is_array($arr))
		{
			foreach($arr as $key=>$val)
			{
				if(!is_numeric($key))
					$this->$key = $val;
			}
		}
	}

	function getObjById($intID, $strFieldName, $strTableName)
	{
		if($intID && $strFieldName && $strTableName)
		{
			global $db;
			$sql = "select * from `$strTableName` where `$strFieldName` = '$intID'";
			$result=$db->query($sql);
			if($row = $db->fetch_array($result, MYSQL_ASSOC))
			{
//				foreach($row as $key=>$val)
//				{
					$this->__construct($row);
//				}
			}
		}
	}
	//update('Template',array('TID'=>2,'TName'=>'fdaskj','Config'=>'fdjasljfdkaljfdk'),'TName,Config','TID')
	function update($tableName, $fields, $idField)
	{
		global $db;
		$sqlStr = "";
		$fList = explode(",", $fields);
		for($i = 0; $i < count($fList); $i++)
		{
			if($i > 0)
			{
				$sqlStr .= ",";
			}
			$sqlStr .= " `{$fList[$i]}`='{$this->$fList[$i]}'";
		}
		$sql = "update $tableName set $sqlStr where `$idField` = '{$this->$idField}'";
		if($db->query($sql))
		{
			return true;
		}
		return false;
	}
	function add($tableName, $fields, $idField)
	{
		global $db;
		if($this->$idField > 0)
			return false;
		$sqlStr = "";
		$fList = explode(",", $fields);
		for($i = 0; $i < count($fList); $i++)
		{
			if($i > 0)
			{
				$sqlStr .= ",";
			}
			$sqlStr .= " `{$fList[$i]}`='{$this->$fList[$i]}'";
		}
		$sql = "insert into $tableName set $sqlStr";
		if($db->query($sql))
		{
			$this->$idField = $db->insert_id();
			$this->__construct($this);
			return true;
		}
		return false;
	}
	//根据parent函数获取所有子项
	function allchildren($grade=0)
	{
		$grade++;
		$allchildren = false;
		if($children = $this->children())
		{
			foreach($children as $child)
			{
				$child->grade = $grade;
				$allchildren[] = $child;
				if($childs = $child->allchildren($grade))
				$allchildren = array_merge($allchildren,$childs);
			}
		}
		return $allchildren;
	}
}

?>